#pragma once

#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include <string>
#include <queue>
#include <semaphore.h>

static const int defaultnum = 5;

struct ThreadInfo
{
    pthread_t tid;
    std::string name;
};

template <class T>
class ThreadPool
{
public:
    void lock()
    {
        pthread_mutex_lock(&_mutex);
    }

    void unlock()
    {
        pthread_mutex_unlock(&_mutex);
    }

    void wakeup()
    {
        pthread_cond_signal(&_cond);
    }

    void threadSleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }

    bool IsQueueEmpty()
    {
        return _tasks.empty();
    }

    std::string GetThreadName(pthread_t tid)
    {
        for (const auto &ti : _threads)
        {
            if (ti.tid == tid)
            {
                return ti.name;
            }
        }
        return "";
    }

    static ThreadPool<T> *GetInstance()
    {
        if (_tp == nullptr)  // 优化，往后的线程可以并发获取单例
        {
            pthread_mutex_lock(&_static_mutex);
            if (_tp == nullptr)
            {
                // std::cout << "log: singleton create done first!" << std::endl;
                _tp = new ThreadPool<T>();
            }
            pthread_mutex_unlock(&_static_mutex);
        }
        return _tp;
    }

public:
    // ThreadPool(int num = defaultnum):_threads(num)
    // {
    //     pthread_mutex_init(&_mutex, nullptr);
    //     pthread_cond_init(&_cond, nullptr);
    // }

    static void *HandlerTask(void *args)
    {
        ThreadPool<T> *tp = static_cast<ThreadPool<T> *>(args);
        std::string name = tp->GetThreadName(pthread_self());
        while (true)
        {
            tp->lock();
            while (tp->IsQueueEmpty())
            {
                tp->threadSleep();
            }
            T t = tp->Pop();
            tp->unlock();
            // 这个任务被线程私有，在加锁外处理
            t();
            std::cout << name << " run, " << "result: " << t.GetResult() << std::endl;
        }
    }

    void Start()
    {
        int num = _threads.size();
        for (int i = 0; i < num; ++i)
        {
            _threads[i].name = "thread-" + std::to_string(i + 1);
            pthread_create(&(_threads[i].tid), nullptr, HandlerTask, this);
        }
    }

    void Push(const T &in)
    {
        lock();
        _tasks.push(in);
        wakeup();
        unlock();
    }

    T Pop()
    {
        T t = _tasks.front();
        _tasks.pop();

        return t;
    }

    // ~ThreadPool()
    // {
    //     pthread_mutex_destroy(&_mutex);
    //     pthread_cond_destroy(&_cond);
    // }

private:
    ThreadPool(int num = defaultnum) : _threads(num)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

    ThreadPool(const ThreadPool<T> &thread) = delete;
    ThreadPool<T> &operator=(const ThreadPool<T> &thread) = delete;

private:
    std::vector<ThreadInfo> _threads;
    std::queue<T> _tasks; // 任务队列

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    static ThreadPool<T> *_tp;
    static pthread_mutex_t _static_mutex;
};

template <class T>
ThreadPool<T> *ThreadPool<T>::_tp = nullptr;

template <class T>
pthread_mutex_t ThreadPool<T>::_static_mutex = PTHREAD_MUTEX_INITIALIZER;